<template>
  <div class="tenant-app">
  

    <div class="page-content">
      <el-card class="app-card">
        <template #header>
          <div class="card-header">
            <span>租户应用列表</span>
            <el-space>
              <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增应用
              </el-button>
              <el-button @click="goBack">
                <el-icon><Back /></el-icon>
                返回租户管理
              </el-button>
            </el-space>
          </div>
        </template>

        <!-- 搜索表单 -->
        <el-form
          v-show="showSearch"
          ref="queryRef"
          :model="queryParams"
          :inline="true"
          label-width="80px"
          class="search-form"
        >
          <el-form-item label="应用类型" prop="appType">
            <el-select v-model="queryParams.appType" placeholder="请选择应用类型" clearable>
              <el-option label="PC端" value="pc" />
              <el-option label="移动端" value="mobile" />
              <el-option label="Web" value="web" />
            </el-select>
          </el-form-item>
          <el-form-item label="应用Key" prop="appKey">
            <el-input 
              v-model="queryParams.appKey" 
              placeholder="请输入应用Key" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item label="应用名称" prop="appName">
            <el-input 
              v-model="queryParams.appName" 
              placeholder="请输入应用名称" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          :data="appList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="应用ID" align="center" prop="appid" width="100" />
          <el-table-column label="应用类型" align="center" prop="appType" width="120">
            <template #default="{ row }">
              <el-tag v-if="row.appType === 'pc'" type="primary">PC端</el-tag>
              <el-tag v-else-if="row.appType === 'mobile'" type="success">移动端</el-tag>
              <el-tag v-else-if="row.appType === 'web'" type="info">Web</el-tag>
              <el-tag v-else>{{ row.appType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="应用Key" align="center" prop="appKey" width="180" show-overflow-tooltip />
          <el-table-column label="应用名称" align="center" prop="appName" width="150" />
          <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
          <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
          <el-table-column label="操作" align="center" fixed="right" width="220">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
              <el-button type="warning" link @click="handleUpdate(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-show="pagination.total > 0"
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </el-card>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @closed="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用类型" prop="appType">
          <el-select v-model="form.appType" placeholder="请选择应用类型" style="width: 100%">
            <el-option label="PC端" value="pc" />
            <el-option label="移动端" value="mobile" />
            <el-option label="Web" value="web" />
          </el-select>
        </el-form-item>
        <el-form-item label="应用Key" prop="appKey">
          <el-input v-model="form.appKey" placeholder="请输入应用Key (请求头 X-APP-KEY)" />
          <div class="form-tip">用于请求头 X-APP-KEY 的值</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="租户应用详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="应用ID">{{ detailData.appid }}</el-descriptions-item>
        <el-descriptions-item label="应用类型">
          <el-tag v-if="detailData.appType === 'pc'" type="primary">PC端</el-tag>
          <el-tag v-else-if="detailData.appType === 'mobile'" type="success">移动端</el-tag>
          <el-tag v-else-if="detailData.appType === 'web'" type="info">Web</el-tag>
          <el-tag v-else>{{ detailData.appType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="应用Key">{{ detailData.appKey }}</el-descriptions-item>
        <el-descriptions-item label="应用名称">{{ detailData.appName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Back, Search, Refresh } from '@element-plus/icons-vue';
import { 
  listTenantApp, 
  getTenantApp, 
  addTenantApp, 
  updateTenantApp, 
  delTenantApp,
  type TenantAppQuery,
  type TenantAppForm,
  type TenantAppVo
} from '@/api/tenant/app';

// 数据状态
const loading = ref(false);
const showSearch = ref(true);
const appList = ref<TenantAppVo[]>([]);
const queryRef = ref();
const formRef = ref();

// 查询参数
const queryParams = reactive<TenantAppQuery>({
  pageNum: 1,
  pageSize: 10,
  appType: undefined,
  appKey: undefined,
  appName: undefined,
});

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref('');
const submitLoading = ref(false);

// 详情对话框
const detailVisible = ref(false);
const detailData = ref<TenantAppVo>({});

// 表单数据
const form = ref<TenantAppForm>({});

// 选择的行
const selectedRows = ref<TenantAppVo[]>([]);
const ids = ref<number[]>([]);

// 表单验证规则
const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' }
  ],
  appType: [
    { required: true, message: '请选择应用类型', trigger: 'change' }
  ],
  appKey: [
    { required: true, message: '请输入应用Key', trigger: 'blur' }
  ],
};

// 获取列表
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    const res: any = await listTenantApp(params);
    appList.value = res.rows || [];
    pagination.total = res.total || 0;
  } catch (error) {
    console.error('获取租户应用列表失败:', error);
    ElMessage.error('获取列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleQuery = () => {
  pagination.current = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryRef.value?.resetFields();
  handleQuery();
};

// 分页变化
const handlePageChange = () => {
  getList();
};

// 表格选择变化
const handleSelectionChange = (selection: TenantAppVo[]) => {
  selectedRows.value = selection;
  ids.value = selection.map(item => item.appid!);
};

// 新增
const handleAdd = () => {
  form.value = {};
  dialogTitle.value = '新增租户应用';
  dialogVisible.value = true;
};

// 查看详情
const handleDetail = async (row: TenantAppVo) => {
  try {
    const res: any = await getTenantApp(row.appid!);
    detailData.value = res.data || {};
    detailVisible.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败');
  }
};

// 编辑
const handleUpdate = async (row: TenantAppVo) => {
  try {
    const res: any = await getTenantApp(row.appid!);
    form.value = res.data || {};
    dialogTitle.value = '编辑租户应用';
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败');
  }
};

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      if (form.value.appid) {
        await updateTenantApp(form.value);
        ElMessage.success('修改成功');
      } else {
        await addTenantApp(form.value);
        ElMessage.success('新增成功');
      }
      dialogVisible.value = false;
      getList();
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error(form.value.appid ? '修改失败' : '新增失败');
    } finally {
      submitLoading.value = false;
    }
  });
};

// 删除
const handleDelete = (row: TenantAppVo) => {
  const appids = row.appid || ids.value;
  ElMessageBox.confirm(
    `是否确认删除应用ID为 ${appids} 的数据项？`,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await delTenantApp(appids as any);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields();
  form.value = {};
};

// 返回租户管理
const goBack = () => {
  window.history.back();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.tenant-app {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}


.page-content {
  .app-card {
    :deep(.el-card__header) {
      padding: 16px 20px;
      border-bottom: 1px solid #e5e6eb;
    }
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-size: 16px;
      font-weight: 500;
      color: #1f2329;
    }
  }
  
  .search-form {
    margin-bottom: 20px;
    
    :deep(.el-form-item) {
      margin-bottom: 16px;
    }
  }
  
  :deep(.el-table) {
    margin-bottom: 20px;
  }
  
  :deep(.el-pagination) {
    justify-content: flex-end;
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}
</style>

